# -*- coding: utf-8 -*-
"""
Created on Fri Mar 31 22:52:08 2017
eULER Project 49
@author: zhiqiang
"""
from math import sqrt
def is_prime(num):#判断一个奇数是不是质数
    is_pri = True
    if num==2:
        return True
    if num==3:
        return True
    for i in range(3,int(sqrt(num))+1,2):
        if num%i==0:
            return False
    return is_pri

if __name__ == "__main__":
    primes_list = {}
    for i in range(1001,10000,2):
        if is_prime(i):
            primes_list[i] = sorted(list(str(i)))

    #找到所有四位的质数
    #寻找所有全排列的质数'
    has_in = []
    has_in_2 = []
    all_keys = primes_list.keys()
    is_ok = True
    for key in all_keys:
        if not is_ok:
            break
        if key in has_in or key in has_in_2:
            continue
        tmp_res = [key]
        tmp = primes_list[key]
        has_in_2.append(key)
        for prime in all_keys:
            if prime in has_in or prime in has_in_2:
                continue
            if tmp==primes_list[prime]:
                has_in.append(prime)
                tmp_res.append(prime)
        len_tmp_res = len(tmp_res)
        if len_tmp_res>=3:
            for i in range(len_tmp_res):
                if not is_ok:
                    break
                if tmp_res[i] in [1487, 4817, 8147]:
                    continue
                for j in range(i+1,len_tmp_res):
                    if tmp_res[j] in [1487, 4817, 8147]:
                        continue
                    if (2*(tmp_res[j]-tmp_res[i]) + tmp_res[i]) in tmp_res:
                        is_ok = False
                        result=(tmp_res[i],tmp_res[j],(2*(tmp_res[j]-tmp_res[i]) + tmp_res[i]))
                        break